/*/////////////////////////////////////////////////////////////////////////////

  The MIT License

  Copyright (c) 2008 - 2010. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

/////////////////////////////////////////////////////////////////////////////*/

package ru.goodcore.composite
{

import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.registerClassAlias;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

//--------------------------------------
//  Events
//--------------------------------------

/**
 * Dispatched when leaf added to branch
 * 
 * @eventType			ru.goodcore.composite.CompositeEvent.ADDED
 */
[Event(name="added", type="ru.goodcore.composite.CompositeEvent")]

/**
 * Dispatched when leaf removed from branch
 * 
 * @eventType			ru.goodcore.composite.CompositeEvent.REMOVED
 */
[Event(name="removed", type="ru.goodcore.composite.CompositeEvent")]

/**
 * Dispatched when leaf added to cradle
 * 
 * @eventType			ru.goodcore.composite.CompositeEvent.ADDED_TO_CRADLE
 * 
 * @see					ru.goodcore.composite.Cradle
 */
[Event(name="addedToCradle", type="ru.goodcore.composite.CompositeEvent")]

/**
 * Dispatched when leaf removed from cradle
 * 
 * @eventType			ru.goodcore.composite.CompositeEvent.REMOVED_FROM_CRADLE
 * 
 * @see					ru.goodcore.composite.Cradle
 */
[Event(name="removedFromCradle", type="ru.goodcore.composite.CompositeEvent")]

/**
 * 
 * @author					Dimarik
 * @version					1.0
 * @playerversion			Flash 9
 * @langversion				3.0
 * 
 */
public class Leaf extends EventDispatcher implements IExternalizable {

	//-------------------------------------------------------------------------
	//
	//  Class constants
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//  Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function Leaf() {
		super();
	}

	//-------------------------------------------------------------------------
	//
	//  Properties
	//
	//-------------------------------------------------------------------------

	//---------------------------------
	//  name
	//---------------------------------

	/**
	 * @private
	 */
	private var _name:	String = "";

	/**
	 * Indicates the instance name of the Leaf object. The object can be 
	 * identified in the child list of its parent branch object container by 
	 * calling the getChildByName() method of the branch object container. 
	 */
	public function get name():String {
		return this._name;
	}

	/**
	 * @private
	 */
	public function set name(value:String):void {
		if ( this._name === value ) return;
		this._name = value;
	}

	//---------------------------------
	//  index
	//---------------------------------

	/**
	 * If the leaf object has a parent, returns the index position of a Leaf instance.
	 * 
	 * @return 							The index position of the child leaf object to identify.
	 * 
	 * @throws	IllegalOperationError	Throws if the leaf object has no parent.
	 * 
	 */
	public function get index():uint {
		if ( !this.parent )
			Error.throwError(IllegalOperationError, 2025);

		return this.parent.getChildIndex(this);
	}

	//---------------------------------
	//  parent
	//---------------------------------

	/**
	 * @private
	 */
	internal var $parent:		Branch;
	
	internal var $storedParent:	Branch;

	/**
	 * Indicates the Branch object that contains this leaf object. Use the parent 
	 * property to specify a relative path to branch objects that are above the 
	 * current leaf object in the composite hierarchy. 
	 * 
	 */
	public function get parent():Branch {
		return this.$parent;
	}

	/**
	 * @private
	 */
	internal function $setParent(value:Branch):void {
		const oldParent:	Branch = this.$parent;

		this.$storedParent = oldParent || value;

		if ( oldParent ) {

			this.dispatchInternalCompositeEvent( Event.REMOVED );

			if ( super.hasEventListener(CompositeEvent.REMOVED_FROM_CRADLE) && oldParent.cradle )
				super.dispatchEvent( new CompositeEvent( 'removedFromCradle', false, false) );
		}

		this.$parent = value;

		if ( value ) {

			this.dispatchInternalCompositeEvent( Event.ADDED );

			if (super.hasEventListener(CompositeEvent.ADDED_TO_CRADLE) && this.cradle)
					super.dispatchEvent( new CompositeEvent( 'addedToCradle', false, false) );

		}

	}

	//---------------------------------
	//  cradle
	//---------------------------------

	/**
	 * The Cradle of the leaf object. If a leaf object is not added to the composite, 
	 * its cradle property is set to null.
	 */
	public function get cradle():Cradle {
		return this.$parent ? this.$parent.cradle : null;
	}

	//-------------------------------------------------------------------------
	//
	//  Private variables
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//  Interface implementation: IExternalizable
	//
	//-------------------------------------------------------------------------

	private var _serializer:	Object;

	protected function get serializer():Object {
		return this._serializer || ( this._serializer = new DefaultSerializer() );
	}

	public function readExternal(input:IDataInput):void {
		this.serializer.target = this;
		this.serializer.readExternal(input);
		this.deserialize(input);
	}

	public function writeExternal(output:IDataOutput):void {
		this.serializer.target = this;
		this.serializer.writeExternal(output);
		this.serialize(output);
	}

	//-------------------------------------------------------------------------
	//
	//  Overridden methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc
	 */
	public override function dispatchEvent(event:Event):Boolean {
		if ( event.bubbles ) {
			if ( event is CompositeEvent ) {
				return this.dispatchCompositeEvent(event as CompositeEvent);
			} else {
				Error.throwError(IllegalOperationError, 2014);
			}
		}
		return super.dispatchEvent(event);
	}

	private function $dispatchEvent(event:Event):Boolean {
		return super.dispatchEvent(event);
	}

	/**
	 * @inheritDoc
	 */
	public override function toString():String {
		return ( this.$parent ? this.$parent+"." : "" ) + ( this._name ? this._name : this.toLocaleString() );
	}

	/**
	 * @inheritDoc
	 */
	public function toLocaleString():String {
		return super.toString();
	}

	//-------------------------------------------------------------------------
	//
	//  Protected methods
	//
	//-------------------------------------------------------------------------

	protected function deserialize(input:IDataInput):void {
		
	}

	protected function serialize(output:IDataOutput):void {
		
	}

	//-------------------------------------------------------------------------
	//
	//  Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 * @param eventType
	 */
	private function dispatchInternalCompositeEvent(eventType:String):void {
		var dispatcher:	Leaf = this;
		var event:		CompositeEvent;

		do {

			if ( dispatcher.hasEventListener(eventType) ) {
				event = new CompositeEvent(eventType);
				event.$target = this;
				$decorator.$event = event;
				dispatcher.$dispatchEvent( $decorator );
			}

			dispatcher = dispatcher.$storedParent;

		} while (dispatcher);

	}

	/**
	 * @private 
	 * @param		event CompositeEvent
	 */
	private function dispatchCompositeEvent(event:CompositeEvent):Boolean {
		var dispatcher:		Leaf = this;
		const eventType:	String = event.type;
		var result:			Boolean = true;

		do {

			if ( dispatcher.hasEventListener(eventType) ) {
				event = event.clone() as CompositeEvent;
				event.$target = this;
				event.$defaultPrevented = !result;
				$decorator.$event = event;
				result = dispatcher.$dispatchEvent( $decorator ) && result;
			}

			dispatcher = dispatcher.$parent;

		} while (dispatcher && event.$notStopped);

		return result;

	}

}
}


//=============================================================================
//
//  Inner definitions
//
//=============================================================================

import flash.events.Event;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

import ru.goodcore.composite.Leaf;

/**
 * @private
 */
internal final class EventDecorator extends Event {

	//-------------------------------------------------------------------------
	//
	//  Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor.
	 */
	public function EventDecorator() {
		super('');
	}

	//-------------------------------------------------------------------------
	//
	//  Variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	internal var $event:	Event;

	//-------------------------------------------------------------------------
	//
	//  Overridden properties: Event
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	public final override function get target():Object {
		return 1;
	}

	//-------------------------------------------------------------------------
	//
	//  Overridden methods: Event
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	public final override function clone():Event {
		return this.$event;
	}

}

/**
 * @private
 */
internal const $decorator:	EventDecorator = new EventDecorator();


/**
 * @private
 */
internal class DefaultSerializer implements IExternalizable {

	public function DefaultSerializer() {
		super();
	}

	public var target:	Leaf;

	public function readExternal(input:IDataInput):void {
		target.name = input.readObject() as String;
	}

	public function writeExternal(output:IDataOutput):void {
		output.writeObject(target.name);
	}

}